package com.neusoft.weixin.service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.neusoft.common.util.WeixinConfigUtil;
import com.neusoft.weixin.message.req.TextMessage;
import com.neusoft.weixin.message.resp.Article;
import com.neusoft.weixin.message.resp.NewsMessage;
import com.neusoft.weixin.service.account.MenuService;
import com.neusoft.weixin.service.person.PersonService;
import com.neusoft.weixin.utils.MessageUtil;


/**
 * 核心服务类
 * 
 */
@Service(value = "coreService")
public class CoreService {
	/**
	 * 处理微信发来的请求
	 * 
	 * @param request
	 * @return
	 */
	
	@Autowired
	private MenuService menuService;
	
	@Autowired
	private PersonService personService;
	
	
	private static final String URL = WeixinConfigUtil.getURL();
	
	private static final Logger LOG = LoggerFactory.getLogger(CoreService.class);
	
	public String processRequest(HttpServletRequest request) {
		LOG.info("处理公众号请求");
		String respMessage = null;
		try {
			// 默认返回的文本消息内容
			String respContent = "请求处理异常，请稍候尝试！";

			// xml请求解析
			Map<String, String> requestMap = MessageUtil.parseXml(request);

			// 发送方帐号（open_id）
			String fromUserName = requestMap.get("FromUserName");
			// 公众帐号
			String toUserName = requestMap.get("ToUserName");
			// 消息类型
			String msgType = requestMap.get("MsgType");
			//消息内容
			String msgContent = requestMap.get("Content");

			// 回复文本消息
			TextMessage textMessage = new TextMessage();
			textMessage.setToUserName(fromUserName);
			textMessage.setFromUserName(toUserName);
			textMessage.setCreateTime(new Date().getTime());
			textMessage.setMsgType(MessageUtil.RESP_MESSAGE_TYPE_TEXT);
			
			NewsMessage newsMessage = new NewsMessage();
			
			// 文本消息
			if (msgType.equals(MessageUtil.REQ_MESSAGE_TYPE_TEXT)) {
				
				Map person = personService.getPersonInfoByOpenId(fromUserName);
				//过滤个人服务的菜单
				if ( null != msgContent && !"21".equals(msgContent) 
						&& msgContent.startsWith("2") ){
					
					if ( null == person ){
						respContent = "请回复21进行个人信息绑定";
						textMessage.setContent(respContent);
						respMessage = MessageUtil.textMessageToXml(textMessage);
						return respMessage;
					}
					
				}
				
				if ( null != msgContent && "21".equals(msgContent) ){
					
					if ( null != person ){
						StringBuffer strBuffer = new StringBuffer();
						strBuffer.append("您的个人信息已绑定，信息如下：\n");
						strBuffer.append("姓名："+person.get("NAME")+"\n");
						strBuffer.append("身份证："+person.get("CARDID")+"\n");
						strBuffer.append("性别："+person.get("SEX")+"\n");
						strBuffer.append("出生日期："+person.get("BIRTHDAY")+"\n");
						strBuffer.append("手机号："+person.get("PHONE")+"\n");
						strBuffer.append("<a href=\""+URL+"/checkStatus?openId="+fromUserName+"\">查看审核状态</a>");
						
						respContent = strBuffer.toString();
						textMessage.setContent(respContent);
						respMessage = MessageUtil.textMessageToXml(textMessage);
						return respMessage;
						
					}
				}
				
				List menus =  menuService.getTopMenu(msgContent);
				if ( menus.size() > 0 ){
					
					LOG.info("获取菜单列表");
					StringBuffer strBuffer = new StringBuffer("欢迎使用本服务号，\n请回复相应序号\n(主菜单请回复0)：\n");
					for ( int i = 0; i < menus.size(); i++ ){
						Map menu = (Map) menus.get(i);
						strBuffer.append(menu.get("MENU_NUM"));
						strBuffer.append("、");
						strBuffer.append(menu.get("MENU_NAME"));
						if ( i < menus.size()-1 ){
							strBuffer.append("\n");
						}
					}
					
					respContent = strBuffer.toString();
					textMessage.setContent(respContent);
					respMessage = MessageUtil.textMessageToXml(textMessage);
				}else{
					LOG.info("无菜单列表");
					LOG.info("查询有无消息反馈");
					List messages = menuService.getMenuMessage(msgContent);
					if ( messages.size() == 0 ){
						LOG.info("无消息反馈");
						respContent = "欢迎您使用本服务号！请回复0获取主菜单。"; 
						textMessage.setContent(respContent);
						respMessage = MessageUtil.textMessageToXml(textMessage);
					}else{
						respMessage = createNewsMessage(fromUserName,
								toUserName, newsMessage, messages);
					}
				}
				
			}
			// 事件推送
			else if (msgType.equals(MessageUtil.REQ_MESSAGE_TYPE_EVENT)) {
				// 事件类型
				String eventType = requestMap.get("Event");
				// 订阅
				if (eventType.equals(MessageUtil.EVENT_TYPE_SUBSCRIBE)) {
					respContent = "谢谢您的关注！";
					textMessage.setContent(respContent);
					respMessage =  MessageUtil.textMessageToXml(textMessage);
				}
				// 取消订阅
				else if (eventType.equals(MessageUtil.EVENT_TYPE_UNSUBSCRIBE)) {
					// 取消订阅后用户再收不到公众号发送的消息，因此不需要回复消息
				}
				// 自定义菜单点击事件
				else if (eventType.equals(MessageUtil.EVENT_TYPE_CLICK)) {
					// 事件KEY值，与创建自定义菜单时指定的KEY值对应
					String eventKey = requestMap.get("EventKey");
					
					LOG.info("自定义菜单被点击，eventKey="+eventKey);
					
					Map person = personService.getPersonInfoByOpenId(fromUserName);
					//过滤个人服务的菜单
					if ( null == person && eventKey.startsWith("2") && !"21".equals(eventKey) ){
						
    					respContent = "请先进行个人信息绑定";
    					textMessage.setContent(respContent);
    					respMessage = MessageUtil.textMessageToXml(textMessage);
    					return respMessage;
						
					}
					
					List messages = menuService.getMenuMessage(eventKey);
					
					if ( messages.size() == 0 ){
						LOG.info("无消息反馈");
					}else{
						respMessage = createNewsMessage(fromUserName,
								toUserName, newsMessage, messages);
					}
					
				}
			}
			
		} catch (Exception e) {
			LOG.error(e.getMessage());
		}

		return respMessage;
	}

	/**
	 * 创建返回消息
	 * @param fromUserName
	 * @param toUserName
	 * @param newsMessage
	 * @param messages
	 * @return
	 */
	private String createNewsMessage(String fromUserName, String toUserName,
			NewsMessage newsMessage, List messages) {
		String respMessage;
		ArrayList<Article> list = new ArrayList<Article>();
		for ( int i = 0; i < messages.size(); i++ ){
			Map<String,String> message = (Map<String,String>) messages.get(i);
			Article article = new Article();
			article.setTitle(message.get("CONTENT_TITLE"));
			article.setPicUrl(URL+message.get("CONTENT_IMG"));
			article.setUrl(URL+message.get("CONTENT_URL")+"?openId="+fromUserName);
			article.setDescription(message.get("CONTENT_DESC"));
			list.add(article);
		}
		newsMessage.setArticleCount(messages.size());
		newsMessage.setCreateTime(new Date().getTime());
		newsMessage.setFromUserName(toUserName);
		newsMessage.setToUserName(fromUserName);
		newsMessage.setArticles(list);
		newsMessage.setMsgType(MessageUtil.RESP_MESSAGE_TYPE_NEWS);
		
		respMessage = MessageUtil.newsMessageToXml(newsMessage);
		return respMessage;
	}
}